package it.trio.monopoly.domain;

import it.trio.monopoly.util.FakeTerminalThatStoresMessage;
import it.trio.monopoly.util.Terminal;

import java.util.ArrayList;
import java.util.List;

public class MGame {
	private static final int MAXIMUM_NUMBER_OF_PLAYERS = 8;
	private static final String[] AVAILABLE_PLAYERS = {"Alice", "Bob", "Chris", "Michael", "Daniel", "Sam", "Jenny", "Carl"}; 
	
	private int actualNumberOfPlayers = 2;
	private List<Player> players;
	private Board board = new Board(); 
	private Die die1 = new RealDie();
	private Die die2 = new RealDie();
	private Terminal terminal;
	private int roundCount;
	
	public MGame(Terminal terminal) {
		this(terminal, new RealDie(), new RealDie());
	}

	public MGame(Terminal terminal, Die die1, Die die2) {
		this.terminal = terminal;
		this.die1 = die1;
		this.die2 = die2;
	}

	public Board getBoard() {
		return board;
	}

	public Die getDie1() {
		return die1;
	}

	public Die getDie2() {
		return die2;
	}

	public int getActualNumberOfPlayers() {
		return actualNumberOfPlayers;
	}

	public List<Player> getPlayers() {
		return players;
	}

	public int  getRoundsCount() {
		return roundCount;
	}

	public void playRound() {
		for(Player p : players)
			p.takeTurn();
	}

	public void startPlay(int numberOfRounds, int numberOfPlayers) {
		createPlayers(numberOfPlayers);
		
		roundCount = 0;
		for(int i=0; i<numberOfRounds; i++) {
			roundCount++;
			playRound();
		}
	}

	public void createPlayers(int numberOfPlayers) {
		if(numberOfPlayers>MAXIMUM_NUMBER_OF_PLAYERS)
			throw new RuntimeException("Too many players");
		
		players = new ArrayList<Player>(numberOfPlayers);
		for(int i=0; i<numberOfPlayers; i++)
			players.add(new Player(AVAILABLE_PLAYERS[i], die1, die2, board, terminal));
	}

	public Player getWinner() {
        Player winner = players.get(0);
        for(Player p : players)
        	if(p.getNetWorth() > winner.getNetWorth())
        		winner = p;
        
		return winner;
	}

}
